﻿
using System.Collections;
using GMS.NET.SqlSugarCore.DbCore;
using GMS.NET.SqlSugarCore.DbSeed;

namespace GMS.NET.Application.Service.System.Tools.Manger
{
    [AllowAnonymous]
    [DynamicApiController]
    public class DataRecoveryService : DbManger, IDataRecoveryService
    {
        public Task FullRecovery()
        {
            var SeedDataTypes = App.EffectiveTypes.Where(u => !u.IsInterface && !u.IsAbstract && u.IsClass
               && u.GetInterfaces().Any(i => i.HasImplementedRawGeneric(typeof(IDataSetRecovery<>)))).ToList();
            if (SeedDataTypes.Any())
            {
                foreach (var seedType in SeedDataTypes)
                {
                    //创建实体
                    var instance = Activator.CreateInstance(seedType);
                    //获取种子数据调用方法对象
                    var hasDataMethod = seedType.GetMethod("HasData");
                    //执行方法获取种子数据
                    var seedData = ((IEnumerable)hasDataMethod?.Invoke(instance, null)!).Cast<object>();
                    if (seedData == null) continue;
                    //获取已创建的实体类型
                    var entityType = seedType.GetInterfaces().First().GetGenericArguments().First();
                    //根据实体类型获取实体信息
                    var entityInfo = MasterDb.EntityMaintenance.GetEntityInfo(entityType);
                    if (entityInfo.Columns.Any(u => u.IsPrimarykey))
                    {
                        // 按主键进行批量增加和更新
                        var storage = MasterDb.StorageableByObject(seedData.ToList()).ToStorage();
                        storage.AsInsertable.ExecuteCommand();
                    }
                    else
                    {
                        // 无主键则只进行插入
                        if (!MasterDb.Queryable(entityInfo.DbTableName, entityInfo.DbTableName).Any())
                            MasterDb.InsertableByObject(seedData.ToList()).ExecuteCommand();
                    }
                }
            }
            return Task.CompletedTask;
        }

        public Task AssignRecovery(string EntityName)
        {
            throw new NotImplementedException();
        }
    }
}
